let n = 0; // 选择音频类型

let timer;

let run_status = 0; // 0 暂停 1 运行

let will_run_task = []

let init_data = []

let tasks_num = 0;
let already_done_tasks = 0;

let dir_png = './res/dir.png';
let start_png = './res/start.png';
let pause_png = './res/pause.png';

let mp3_png = './res/mp3.png';
let mp4_png = './res/mp4.png';
let wav_png = './res/wav.png';

let pause_text = '已暂停'
let start_text = '执行中'
let finish_text = '已完成'
let wait_text = '等待中'

function video_read(text,x){
    n = x;

    let item = document.getElementsByClassName("pop");

    item[0].style.cssText = "display:block";
    
    document.getElementsByClassName("pop-notice")[0].innerHTML = text;

}

function file_path(){
    let result = pywebview.api.select_file(n);

    result.then((result)=>{
        document.getElementById("f-path").value = result;
    })
}

function save_path(){
    let result = pywebview.api.save_file();

    result.then((result)=>{
        console.log(result);
        document.getElementById("save-path").value = result;
    })
}

function pop_close(){
    let item = document.getElementsByClassName("pop");

    item[0].style.cssText = "display:none";
}

function task_div(t,num,path,text1,file_type){
    let f_t = '';

    if(file_type == "mp3"){
        f_t = mp3_png;
    }else if(file_type == "mp4"){
        f_t = mp4_png;
    }else if(file_type == "wav"){
        f_t = wav_png;
    }

    let text = '<div class="block"><div class="vimg flex-center"><img src="'+f_t+'"/></div>'+
            '<div class="pross-panel"><div class="vname">'+
            t+
            '</div><div class="pbar"><div class="progress">'+
            '<div class="progress-bar" role="progressbar" aria-valuenow="70" aria-valuemin="0" aria-valuemax="100" style="width:'+num+'0%">'+
            '</div></div></div></div><div class="ctl">'+
            '<button onclick="btn_click(this)"><img src="'+path+'"/></button><div class="notice">'+text1+'</div>'+
            '</div><div class="delete" onclick="delete_task(this)">删除</div></div>';
    return text
}


function btn_click(Obj){
    let brother1 = Obj.parentNode.parentNode.children[1];
    let name = brother1.getElementsByClassName("vname")[0].innerHTML;
    let notice = Obj.parentNode.children[1];
    let pross_bar = brother1.getElementsByClassName("progress-bar")[0];

    let file_type = Obj.getElementsByTagName("img")[0].src;

    file_type = file_type.split('/');

    file_type = './' + file_type[file_type.length-2] +'/'+ file_type[file_type.length-1]

    if(file_type == start_png){ // 未开始
        let r1 = pywebview.api.single_task_run(name);
        r1.then((result)=>{
            Obj.children[0].src = pause_png;
            pross_bar.style.cssText = "width:50%;";
            notice.innerHTML = start_text;
            let footer = document.getElementsByClassName("footer")[0].getElementsByTagName("div")[0]; 
            footer.innerHTML = "正在识别，请耐心等待....";
            // let tr = setInterval(()=>{single_monitor(name);},2000);
            // timers.push(tr);
            setInterval(monitor,2000);
        })
        

    }else if(file_type == pause_png){  //暂停
        let r2 = pywebview.api.single_task_stop(name);
        r2.then((result)=>{
            Obj.children[0].src = start_png;
            Obj.parentNode.children[1].innerHTML = pause_text;
            will_run_task.remove(name);
            
            // for(let i =0;i<timers.length;i++){

            // }
            // clearInterval(timer);
        })
        
    }else{
        // Obj.children[0].src = start_png;
        pywebview.api.open_explore(name);
    }
}


function init(){
    let result = pywebview.api.task_show();

    let root = document.getElementsByClassName("pross")[0];
    result.then((result)=>{
        if(result){
            console.log(result);
            tasks_num = result.length;
            for(let i=0;i<result.length;i++){
                
                if(result[i]["status"] == 1){
                    // 已完成
                    root.innerHTML += task_div(result[i]["file_name"],100,dir_png,finish_text,result[i]["file_type"]);
                    already_done_tasks++;
                }else{
                    will_run_task.push(result[i]['file_name'])
                    root.innerHTML += task_div(result[i]["file_name"],0,start_png,pause_text,result[i]["file_type"]);
                }
            }

            document.getElementsByClassName("msg")[0].innerHTML = '完成('+already_done_tasks+'/'+tasks_num+')';
        }
    })

}

setTimeout(function(){
    //1秒后执行刷新
    init();
}, 1000); //单位是毫秒

function confirm(){
    let root = document.getElementsByClassName("pross")[0];
    let file_path = document.getElementById("f-path").value;
    let save_path = document.getElementById("save-path").value;
    let is_cpu = document.getElementById("is_cpu");
    let s_language = document.getElementById("language");
    let s_model = document.getElementById("model");

    let index = is_cpu.selectedIndex;
    let cpu_gpu = is_cpu.options[index].value;
    let index2 = s_language.selectedIndex;
    let language = s_language.options[index2].value;
    let index3 = s_model.selectedIndex;
    let model = s_model.options[index3].value;

    let result = pywebview.api.make_task(file_path,save_path,cpu_gpu,language,model);

    tasks_num++;
    document.getElementsByClassName("msg")[0].innerHTML = '完成('+already_done_tasks+'/'+tasks_num+')';
    result.then((result)=>{

        
        root.innerHTML += task_div(result[0],0,start_png,wait_text,result[1]);

        document.getElementsByClassName("pop")[0].style.cssText="display:none;";
    })
    
}

function monitor(){

    let result = pywebview.api.monitor();

    result.then((result)=>{
        console.log(result)
        if(result.length == 0){
            clearInterval(timer); //清空定时器
            let footer = document.getElementsByClassName("footer")[0].getElementsByTagName("div")[0]; 
            footer.innerHTML = "识别任务已经全部完成！";
            document.getElementsByClassName("run")[0].innerHTML = '<img src="./res/start.png"/>开始';

        }else{
            for(let i=0;i<result.length;i++){
                if(result[i]['status'] == 1){
                    let items = document.getElementsByClassName("pross-panel");
                    
                    for(let j =0;j<items.length;j++){
                        let vname = items[j].getElementsByClassName("vname")[0];
                        
                        if(vname.innerHTML == result[i]["name"]){
                            items[j].getElementsByClassName("progress-bar")[0].style.cssText = "width:100%;";
                            let brother1 = items[j].parentNode.children[2];
                            brother1.getElementsByTagName("button")[0].getElementsByTagName("img")[0].src = dir_png;
                            brother1.getElementsByClassName("notice")[0].innerHTML = finish_text;
                
                        }
                    }
                    already_done_tasks++;
                    document.getElementsByClassName("msg")[0].innerHTML = '完成('+already_done_tasks+'/'+tasks_num+')';
                }
            }   
        }

    })
}

function run(){

    if(run_status == 0){
        let result = pywebview.api.task_run_show();

        result.then((result)=>{
            for(let k =0;k<result.length;k++){
                will_run_task.push(result[k]["file_name"]);
            }
        }).then(()=>{
            if(will_run_task.length == 0){
                alert("没有可以运行的任务!");
                clearInterval(timer);
                return null;
            }
            run_status = 1
            document.getElementsByClassName("run")[0].innerHTML = '<img src="./res/pause.png"/>暂停';
            for(let i = 0;i<will_run_task.length;i++){
                let items = document.getElementsByClassName("pross-panel");      
                for(let j =0;j<items.length;j++){
                    let vname = items[j].getElementsByClassName("vname")[0];
                    if(vname.innerHTML == will_run_task[i]){
                        items[j].getElementsByClassName("progress-bar")[0].style.cssText = "width:50%;";
                        let brother1 = items[j].parentNode.children[2];
                        brother1.getElementsByTagName("button")[0].getElementsByTagName("img")[0].src = pause_png;
                        brother1.getElementsByClassName("notice")[0].innerHTML = start_text;
                    }
                }
            }
            let footer = document.getElementsByClassName("footer")[0].getElementsByTagName("div")[0]; 
            footer.innerHTML = "正在识别，请耐心等待....";



            pywebview.api.run();
    
            timer = setInterval(monitor,2000);
        })
        
    }else{
        run_status = 0
        document.getElementsByClassName("run")[0].innerHTML = '<img src="./res/start.png"/>运行';
        let result = pywebview.api.task_stop();
        let footer = document.getElementsByClassName("footer")[0].getElementsByTagName("div")[0]; 
        footer.innerHTML = "识别任务终止";
    }
    


}


function delete_task(Obj){

    let brother1 = Obj.parentNode.children[1];
    let name = brother1.getElementsByClassName("vname")[0].innerHTML;

    tasks_num--;
    init_data = pywebview.api.task_show();

    init_data.then((result)=>{

        for(let i = 0; i< result.length;i++){
            if(name == result[i]["file_name"] && result[i]["status"] == 1){
                already_done_tasks -= 1;
                break;
            }
        }
    }).then(()=>{
        let result = pywebview.api.delete_task(name);

        result.then((result)=>{
            if(result){  //为真
                Obj.parentNode.parentNode.removeChild(Obj.parentNode);
                let footer = document.getElementsByClassName("footer")[0].getElementsByTagName("div")[0];
                footer.innerHTML = "删除文件成功!";
            }

        })
    }).then(()=>{
        document.getElementsByClassName("msg")[0].innerHTML = '完成('+already_done_tasks+'/'+tasks_num+')';
    })
}


function change_theme(types){
    if(types == 1){
        document.getElementsByClassName("out-box")[0].style.cssText = "background-color:#d5c59f;";
    }
    else{
        document.getElementsByClassName("out-box")[0].style.cssText = "background-color:#131124;";
    }
    
}

window.alert = function(str)
{
    var shield = document.createElement("DIV");
    shield.id = "shield";
    shield.style.position = "absolute";
    shield.style.left = "50%";
    shield.style.top = "50%";
    shield.style.width = "280px";
    shield.style.height = "150px";
    shield.style.marginLeft = "-140px";
    shield.style.marginTop = "-110px";
    shield.style.zIndex = "25";
    var alertFram = document.createElement("DIV");
    alertFram.id="alertFram";
    alertFram.style.position = "absolute";
    alertFram.style.width = "280px";
    alertFram.style.height = "150px";
    alertFram.style.left = "50%";
    alertFram.style.top = "50%";
    alertFram.style.marginLeft = "-140px";
    alertFram.style.marginTop = "-110px";
    alertFram.style.textAlign = "center";
    alertFram.style.lineHeight = "150px";
    alertFram.style.zIndex = "300";
    strHtml = "<ul style=\"list-style:none;margin:0px;padding:0px;width:100%\">\n";
    strHtml += " <li style=\"background:#72baa7;text-align:left;padding-left:20px;font-size:14px;font-weight:bold;height:25px;line-height:25px;border:1px solid #F9CADE;color:white\">提示</li>\n";
    strHtml += " <li style=\"background:#72baa7;color:#ffc20e;text-align:center;font-size:16px;height:95px;line-height:95px;border-left:1px solid #F9CADE;border-right:1px solid #F9CADE;color:#DCC722\">"+str+"</li>\n";
    strHtml += " <li style=\"background:#72baa7;text-align:center;font-weight:bold;height:30px;line-height:25px; border:1px solid #F9CADE;\"><input type=\"button\" value=\"确 定\" onclick=\"doOk()\" style=\"width:80px;height:20px;background:#626262;color:white;border:1px solid white;font-size:14px;line-height:20px;outline:none;margin-top: 4px\"/></li>\n";
    strHtml += "</ul>\n";
    alertFram.innerHTML = strHtml;
    document.body.appendChild(alertFram);
    document.body.appendChild(shield);
    this.doOk = function(){
        alertFram.style.display = "none";
        shield.style.display = "none";
    }
    alertFram.focus();
    document.body.onselectstart = function(){return false;};
}